<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>本月: 社保在缴 公积金在缴</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button v-allow="'导入'" type="warning" size="small" @click="$router.push('/import')">导入excel</el-button>
          <el-button v-allow="'导出'" type="danger" size="small" @click="hExportExcel">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </PageTools>
      <el-card style="margin-top: 10px">
        <el-table border :data="list" :default-sort="{prop: 'timeOfEntry'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <!-- 额外组件 -->
              <ImageHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template v-slot="scope">
              {{ formatType(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作" width="280">
            <template v-slot="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="total, sizes,prev, pager, next, jumper"
            :total="total"
            :page-size="size"
            :page-sizes="[2,5,10]"
            @current-change="hCurrentChange"
            @size-change="hSizeChange"
          />
        </el-row>
      </el-card>
    </div>
    <el-dialog title="新增员工" :visible.sync="showDialog">
      <addor-edit @close="showDialog=false" @success="hSuccess" />
    </el-dialog>
    <!-- 使用分配角色组件 -->
    <el-dialog
      :visible.sync="showDialogRole"
      title="分配角色"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <AssignRole v-if="showDialogRole" :id="curId" @close="showDialogRole=false" />
    </el-dialog>
  </div>
</template>

<script>
import AssignRole from './assignRole'
import addorEdit from './empDialog'
import { getEmployees, delEmployees } from '@/api/employees'
import employeesEnum from '@/constant/employees'
const hireType = employeesEnum.hireType.reduce((acc, item) => { return { ...acc, [item.id]: item.value } }, {})

export default {
  name: 'Employees',
  components: {
    addorEdit, AssignRole
  },
  data() {
    return {
      curId: '', // 当前的员工编号
      showDialogRole: false, // 分配角色
      showDialog: false, // 新增
      page: 1, // 当前页码
      size: 5, // 每页几条
      total: 0, // 总共数据条数
      list: []
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    // 员工信息渲染
    async loadEmployees() {
      try {
        const res = await getEmployees({ page: this.page, size: this.size })
        console.log('12', res)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (err) {
        console.log(err)
        this.$message.error('加载员工数据失败')
      }
    },
    // 聘用形式表格数据格式化
    formatType(typeId) {
      return hireType[typeId] || '未知'
    },

    // 切换页码
    hCurrentChange(curPage) {
      // 1. 更新页码
      this.page = curPage
      // 2. 重发请求
      this.loadEmployees()
    },
    // 每页几条
    hSizeChange(curSize) {
      this.page = 1
      // 1. 更新每页的条数
      this.size = curSize
      // 2. 重发请求
      this.loadEmployees()
    },

    // 删除
    async doDel(id) {
      try {
        const res = await delEmployees(id)
        console.log('delEmployee', res)
        // 提示
        this.$message.success('删除成功')
        // 如果删除第最后一页的最一条数据之后，页面会显示不正常
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        // 重发请求
        this.loadEmployees()
      } catch (err) {
        console.log('delEmployee', err)
        this.$message.error('删除失败')
      }
    },
    hDel(id) {
      // 确认框
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.doDel(id)
        })
        .catch((err) => {
          console.log(err)
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    // 收到子组件抛出的添加成功的事件
    hSuccess() {
      this.showDialog = false
      // 添加成功，进入最后一页看数据
      this.total++
      // 最后一页
      this.page = Math.ceil(this.total / this.size)
      this.loadEmployees()
    },

    // 导出
    hExportExcel() {
      // 导出数据为excel
      import('@/vendor/Export2Excel').then(async excel => {
        // excel表示导入的模块对象
        const res = await getEmployees({ page: this.page, size: this.size })
        const list = res.data.rows
        console.log('从后端获取的数据', list)
        const { header, data } = this.formatData(list)
        // excel表示导入的模块对象
        console.log(header, data)
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      let header = []
      // header = ['id', 'mobile', 'username', .....]
      // data = [
      //     ['65c2', '1380000002', '管理员', ....],
      //     ['65c3', '1380000003', '孙财', ....],
      // ]
      let data = []
      // 开始代码
      // 找到一个元素
      const one = list[0]
      if (!one) {
        return { header, data }
      }
      header = Object.keys(one).map(key => {
        return map[key]
      })
      // data把list中每一个对象转成 对应的value数组
      data = list.map(obj => {
        return Object.values(obj)
      })

      return { header, data }
    },

    // 分配角色
    hAssignRole(id) {
      this.showDialogRole = true
      this.curId = id
    }
  }
}
</script>
